package top.psjj.mall.controller;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.psjj.mall.comment.Result;
import top.psjj.mall.model.dto.AddCategoryReq;
import top.psjj.mall.model.dto.UpdateCategoryReq;
import top.psjj.mall.model.po.Category;
import top.psjj.mall.model.vo.CategoryVo;
import top.psjj.mall.service.api.CategoryService;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

@RestController
@Validated //单个参数校验支持注解
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    //后台产品类别添加功能
    @PostMapping("/admin/category/add")
    public Result add(@RequestBody @Valid AddCategoryReq addCategoryReq){
        //1.将dto对象转为po对象
        Category category = new Category();
        BeanUtils.copyProperties(addCategoryReq,category);
        //2.插入产品分类数据
        categoryService.add(category);
        return Result.success();
    }
    //后台产品修改
    @PostMapping("/admin/category/update")
    public Result update(@RequestBody @Valid UpdateCategoryReq updateCategoryReq){
        //1.将dto转为po对象
        Category category = new Category();
        BeanUtils.copyProperties(updateCategoryReq,category);
        //2.修改数据
        categoryService.update(category);
        return Result.success();
    }
    //后台删除产品类别
    @PostMapping("/admin/category/delete")
    public Result delete(
            @RequestParam(value = "id",required = false)
            @NotNull(message = "id不能为null") Integer id){
        categoryService.delete(id);
        return Result.success();
    }
    //后台产品类别分页
    @GetMapping("/admin/category/list")
    public Result listForAdmin(
            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize
            ){
        PageInfo pageInfo = categoryService.listForAdmin(pageNum,pageSize);
        return Result.success(pageInfo);
    }
    //前台三级目录
    @GetMapping("/category/list")
    public Result listForCustomer(){
        List<CategoryVo> result = categoryService.listForCustomer();
        return Result.success(result);
    }
}
